package com.yanqu.road.server.manger.activity.zhenhuan;

import com.yanqu.road.dao.impl.activity.zhenhuan.UserZhenHuanPartyHistoryDaoImpl;
import com.yanqu.road.dao.impl.player.UserZhenHuanSecondDaoImpl;
import com.yanqu.road.entity.activity.zhenhuan.secondProcess.GameZhenHuanFinishPartyData;
import com.yanqu.road.entity.activity.zhenhuan.secondProcess.UserZhenHuanPartyHistoryData;
import com.yanqu.road.entity.activity.zhenhuan.secondProcess.UserZhenHuanSecondProcessData;
import com.yanqu.road.entity.activity.zhenhuan.secondProcess.ZhenHuanPartyUserSimpleInfo;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.log.LogZhenHuanThirdBanquetSettle;
import com.yanqu.road.entity.player.PlayerState;
import com.yanqu.road.logic.activity.zhenhuan.ZhenHuanSecondProcessConfig;
import com.yanqu.road.logic.activity.zhenhuan.ZhenHuanThirdProcessConfig;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.ZhenHuanProto;
import com.yanqu.road.pb.player.PlayerProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.zhenhuan.ZhenHuanSecondProcessModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.maidian.DefaultEventTraceAction;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.rank.ActivityRankMgr;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.executor.GeneralTask;
import com.yanqu.road.utils.property.Property;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ZhenHuanTask extends GeneralTask {
    private int code;
    private long userId;
    private byte[] bytes;

    public ZhenHuanTask(int code, long userId, byte[] bytes) {
        this.code = code;
        this.userId = userId;
        this.bytes = bytes;
    }

    @Override
    public void doRun() {
        try {
            if (code == GameProtocol.S_ZHENHUAN_THIRD_PROCESS_BANQUET_SCORE_NOTICE_FROM_CROSS) {
                ZhenHuanThirdProcessConfig config = ZhenHuanConfigMgr.getThirdProcessConfig();
                if (config == null) {
                    return;
                }
                ZhenHuanProto.CrossZhenHuanThirdProcessBanquetScoreNotifyMsg reqMsg = ZhenHuanProto.CrossZhenHuanThirdProcessBanquetScoreNotifyMsg.parseFrom(bytes);
                if (config.getActivityInfo().getActivityId() != reqMsg.getActivityId()) {
                    return;
                }

                GamePlayer player = GamePlayerMgr.getPlayer(userId);
                if (player != null) {
                    Property reward = new Property(config.getExchangeScoreId(), reqMsg.getAddScore());
                    player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.ZhenHuanThirdProcess, eLogMoneyType.ZhenHuanThirdProcessOpenBanquetGet);
                    // 更新一下
                    player.notifyListener(eGamePlayerEventType.ZhenHuanThirdProcessRank.getValue(), reqMsg.getScore());
                    //同步给客户端
                    if (player.getState() == PlayerState.ONLINE) {//玩家在线才执行
                        ZhenHuanProto.ZhenHuanThirdProcessSettleSyncMsg.Builder builder = ZhenHuanProto.ZhenHuanThirdProcessSettleSyncMsg.newBuilder();
                        builder.setActivityId(reqMsg.getActivityId());
                        builder.setUserId(reqMsg.getUserId());
                        builder.setBanquetId(reqMsg.getBanquetId());
                        builder.setScore(reqMsg.getScore());
                        builder.setAddScore(reqMsg.getAddScore());
                        player.sendPacket(Protocol.U_ZHENHUAN_THIRD_PROCESS_SETTLE_SYNC, builder);
                    }
                    AutoLogMgr.add(new LogZhenHuanThirdBanquetSettle(config.getActivityId(), player.getUserId(), reqMsg.getBanquetId(), reqMsg.getAddScore(), reward.toHelperString()));
                    try {
                        DefaultEventTraceAction action = new DefaultEventTraceAction("zhguest_thirend", player);
                        action.build("activityid", config.getActivityId());
                        action.build("zhguest_thirid", reqMsg.getBanquetId());
                        action.build("zhguest_thirendscore", reqMsg.getAddScore());
                        action.build("zhguest_thirendget", reward.toHelperString());
                        action.trace();
                    } catch (Exception e) {
                        getLOGGER().error("ZhenHuanTask.doRun {}", e);
                    }
                }
            } else if (code == GameProtocol.S_ZHENHUAN_SECOND_PROCESS_PARTY_FINISH_CROSS_BACK) {
                ZhenHuanProto.CrossZhenHuanSecondProcessFinishPartySyncMsg syncMsg = ZhenHuanProto.CrossZhenHuanSecondProcessFinishPartySyncMsg.parseFrom(bytes);
                ZhenHuanSecondProcessConfig secondProcessConfig = ZhenHuanConfigMgr.getSecondProcessConfig();
                if (secondProcessConfig == null) {
                    return;
                }

                if (secondProcessConfig.getActivityId() != syncMsg.getActivityId()) {
                    return;
                }
                Map<Long, Long> userTotalAddPrestigeMap = new HashMap<>();// 汇总玩家增加的声望
                Map<Long, List<UserZhenHuanPartyHistoryData>> userHistoryDataMap = new HashMap<>();//汇总的玩家新增结算宴会

                for (ZhenHuanProto.ZhenHuanSecondProcessPartyDetailTemp detailTemp : syncMsg.getPartyDetailListList()) {
                    GameZhenHuanFinishPartyData finishPartyData = ZhenHuanMgr.getFinishPartyData(syncMsg.getActivityId(), detailTemp.getPartyId());
                    if (finishPartyData == null) {//生成游戏服的结算数据
                        finishPartyData = new GameZhenHuanFinishPartyData(syncMsg.getActivityId(), detailTemp.getPartyId());
                        finishPartyData.setFinishTime(DateHelper.getCurrentTime());
                        finishPartyData.setPartyLevel(detailTemp.getOpenLevel());

                        List<ZhenHuanPartyUserSimpleInfo> joinUserList = new ArrayList<>();
                        for (ZhenHuanProto.ZhenHuanSecondProcessPartyPlayerTemp joinTemp : detailTemp.getPlayerListList()) {
                            long userId = joinTemp.getUserId();
                            if (!joinTemp.getIsNpc()) {//npc没有userBaseInfo
                                PlayerProto.PlayerBaseTempMsg userBaseInfo = joinTemp.getUserBaseInfo();
                                if (userBaseInfo.getServerId() == GameServer.getInstance().getServerId()) {
                                    Long addValue = userTotalAddPrestigeMap.getOrDefault(userId, 0L);
                                    addValue += joinTemp.getFinishPrestige();
                                    userTotalAddPrestigeMap.put(userId, addValue);

                                    //本服玩家加到玩家身上
                                    UserZhenHuanPartyHistoryData userZhenHuanPartyHistoryData = new UserZhenHuanPartyHistoryData(syncMsg.getActivityId(), userId, detailTemp.getPartyId(), detailTemp.getEndTime());
                                    userZhenHuanPartyHistoryData.setPos(joinTemp.getPos());
                                    userZhenHuanPartyHistoryData.setReward(secondProcessConfig.parsePrestigeRewardString(joinTemp.getFinishPrestige()));

                                    List<UserZhenHuanPartyHistoryData> userHistoryDataList = userHistoryDataMap.get(userId);
                                    if (userHistoryDataList == null) {
                                        userHistoryDataList = new ArrayList<>();
                                        userHistoryDataMap.put(userId, userHistoryDataList);
                                    }
                                    userHistoryDataList.add(userZhenHuanPartyHistoryData);
                                }

                                if (joinTemp.getPos() == 1) {
                                    finishPartyData.setOpenServerId(userBaseInfo.getServerId());
                                    finishPartyData.setOpenUserId(joinTemp.getUserId());
                                    finishPartyData.setUserName(userBaseInfo.getNickName());
                                    finishPartyData.setUserDecoration(userBaseInfo.getDecoration());
                                }

                                ZhenHuanPartyUserSimpleInfo userSimpleInfo = new ZhenHuanPartyUserSimpleInfo();
                                userSimpleInfo.setUserId(userId);
                                userSimpleInfo.setServerId(userBaseInfo.getServerId());
                                userSimpleInfo.setUserName(userBaseInfo.getNickName());
                                userSimpleInfo.setLevel(joinTemp.getLevel());
                                userSimpleInfo.setPrestige(joinTemp.getUserPrestige());
                                userSimpleInfo.setMatchPrestige(joinTemp.getFinishPrestige());
                                userSimpleInfo.setPos(joinTemp.getPos());
                                userSimpleInfo.setUserDecoration(userBaseInfo.getDecoration());

                                joinUserList.add(userSimpleInfo);
                            } else {//npc
                                ZhenHuanPartyUserSimpleInfo userSimpleInfo = new ZhenHuanPartyUserSimpleInfo();
                                userSimpleInfo.setUserId(userId);
                                userSimpleInfo.setServerId(0);
                                userSimpleInfo.setUserName("");
                                userSimpleInfo.setLevel(joinTemp.getLevel());
                                userSimpleInfo.setPrestige(joinTemp.getUserPrestige());
                                userSimpleInfo.setMatchPrestige(joinTemp.getFinishPrestige());
                                userSimpleInfo.setPos(joinTemp.getPos());
                                userSimpleInfo.setUserDecoration("");

                                joinUserList.add(userSimpleInfo);
                            }
                        }

                        finishPartyData.setJoinUserList(joinUserList);

                        ZhenHuanMgr.addFinishPartyData(syncMsg.getActivityId(), finishPartyData);
                    }

                }

                for (Map.Entry<Long, Long> entry : userTotalAddPrestigeMap.entrySet()) {
                    Long userId = entry.getKey();
                    Long addPrestige = entry.getValue();

                    List<UserZhenHuanPartyHistoryData> historyList = userHistoryDataMap.getOrDefault(userId, new ArrayList<>());

                    GamePlayer onlinePlayer = GamePlayerMgr.getPlayer(userId);
                    if (onlinePlayer != null) {
                        onlinePlayer.getModule(ZhenHuanSecondProcessModule.class).addPartyHistory(historyList, addPrestige);
                    }
                }
            }

        } catch (Exception e) {
            getLOGGER().error("ZhenHuanTask doRun error", e);
        }
    }
}
